﻿using System;
using System.ComponentModel;
using System.Diagnostics.Contracts;

namespace OpenWaves.Web.Controls
{
    [Serializable]
    [TypeConverter(typeof(GeoRectangleConverter))]
    public class GeoRectangle
    {
        private readonly GeoPoint topLeft;
        public GeoPoint TopLeft
        {
            get { return this.topLeft; }
        }

        private readonly GeoPoint bottomRight;
        public GeoPoint BottomRight
        {
            get { return this.bottomRight; }
        }

        public GeoRectangle(GeoPoint topLeft, GeoPoint bottomRight)
        {
            this.topLeft = topLeft;
            this.bottomRight = bottomRight;
        }

        public GeoRectangle Extend(GeoPoint newPoint)
        {
            var newTopLeft = new GeoPoint(
                newPoint.Latitude > this.TopLeft.Latitude ? newPoint.Latitude : this.TopLeft.Latitude,
                newPoint.Longitude < this.TopLeft.Longitude ? newPoint.Longitude : this.TopLeft.Longitude);


            var newBottomRight = new GeoPoint(
                newPoint.Latitude < this.BottomRight.Latitude ? newPoint.Latitude : this.BottomRight.Latitude,
                newPoint.Longitude > this.BottomRight.Longitude ? newPoint.Longitude : this.BottomRight.Longitude);

            return new GeoRectangle(newTopLeft, newBottomRight);
        }

        public static GeoRectangle Parse(string value)
        {
            Contract.Requires<ArgumentNullException>(String.IsNullOrEmpty(value) == false);

            string[] stringArray = value.Split(';');
            if (stringArray.Length != 2)
            {
                throw new FormatException("String should be in format \"(lat,lng);(lat,lng)\"");
            }

            return new GeoRectangle(
                GeoPoint.Parse(stringArray[0].Trim().TrimStart('(').TrimEnd(')')), 
                GeoPoint.Parse(stringArray[1].Trim().TrimStart('(').TrimEnd(')')));
        }
    }
}
